package com.api;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DDLApi {

    private Configuration conf;
    private Connection conn;
    private Admin admin;

    @Before
    public void init() throws IOException {
        // 创建配置文件
        conf = HBaseConfiguration.create();
        // 加载zookeeper的配置
        conf.set("hbase.zookeeper.quorum", "node02,node03,node04");
        // 获取连接
        conn = ConnectionFactory.createConnection(conf);
        // 获取admin对象
        admin = conn.getAdmin();
    }


    //删除表
    @Test
    public void deleteTable() throws IOException {
        TableName tableName = TableName.valueOf("default", "t1");
        admin.disableTable(tableName);
        admin.deleteTable(tableName);
    }

    // 创建表
    @Test
    public void createTable() throws IOException {
        TableName tableName = TableName.valueOf("api_test:student1");
        // 得到表描述
        TableDescriptorBuilder tableBuilder = TableDescriptorBuilder.newBuilder(tableName);

        boolean flag = admin.tableExists(tableName);
        if (flag) {
            System.out.println("table exists, not create");
            return;
        }

        String[] arr = {"info"};

        List<ColumnFamilyDescriptor> list = new ArrayList<>();

        for (String cf : arr) {
            // 创建列族的builder
            ColumnFamilyDescriptorBuilder cfBuilder = ColumnFamilyDescriptorBuilder.newBuilder(cf.getBytes());

            // 设置列族版本
            cfBuilder.setMaxVersions(1);

            // 设置布隆过滤器
            cfBuilder.setBloomFilterType(BloomType.ROWCOL);

            list.add(cfBuilder.build());
        }

        // 列族集合设置到表中
        tableBuilder.setColumnFamilies(list);


        // 创建表
        admin.createTable(tableBuilder.build());
    }


    // 判断表格是否存在
    @Test
    public void existsTable() throws IOException {
        TableName tableName = TableName.valueOf("default:t_user");
        boolean flag = admin.tableExists(tableName);
        System.out.println(flag);
    }

    /**
     * 创建命名空间
     *
     * @throws Exception 套路，先create，再build
     */
    @Test
    public void createNameSpace() throws Exception {
        String nameSpace = "api_test1";
        // 创建命令空间描述建造者
        NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(nameSpace);
        // 调用api创建命名空间
        admin.createNamespace(builder.build());
    }

    @Test
    public void test1() {
        System.out.println(conn);
        System.out.println(admin);
    }


    @After
    public void afterTest() throws IOException {
        admin.close();
        conn.close();
    }
}
